package com.song.yunpicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.song.yunpicturebackend.constant.UserConstant;
import com.song.yunpicturebackend.exception.BusinessException;
import com.song.yunpicturebackend.exception.ErrorCode;
import com.song.yunpicturebackend.model.dto.user.UserLoginReq;
import com.song.yunpicturebackend.model.dto.user.UserQueryReq;
import com.song.yunpicturebackend.model.dto.user.UserRegisterReq;
import com.song.yunpicturebackend.model.entity.User;
import com.song.yunpicturebackend.model.enums.UserRoleEnum;
import com.song.yunpicturebackend.model.vo.LoginUserVO;
import com.song.yunpicturebackend.model.vo.UserVO;
import com.song.yunpicturebackend.service.UserService;
import com.song.yunpicturebackend.mapper.UserMapper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2024-12-28 14:13:07
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    /**
     * 是否为管理员
     * @param user
     * @return
     */
    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }


    /**
     * 用户注册
     * @param userRegisterReq
     * @return
     */
    @Override
    public long userRegister(UserRegisterReq userRegisterReq) {
        //1、校验参数
        if (StrUtil.hasBlank(userRegisterReq.getUserPassword(),userRegisterReq.getUserAccount(),userRegisterReq.getCheckPassword())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userRegisterReq.getUserAccount().length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userRegisterReq.getUserPassword().length() < 8 || userRegisterReq.getCheckPassword().length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (!userRegisterReq.getUserPassword().equals(userRegisterReq.getCheckPassword())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }

        //2、检验用户账号是否和数据库中已有的重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userRegisterReq.getUserAccount());
        long count = this.baseMapper.selectCount(queryWrapper);
        if (count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }

        //3、密码一定要加盐
        String encryptPassword = getEncryptPassword(userRegisterReq.getUserPassword());

        //4、插入数据到数据库中
        User user = new User();
        user.setUserAccount(userRegisterReq.getUserAccount());
        user.setUserPassword(encryptPassword);
        user.setUserName("无名");
        user.setUserRole(UserRoleEnum.USER.getValue());
        boolean saveResult = this.save(user);
        if (!saveResult){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据可错误");
        }
        //mybatis自动生成的ID，主键回填
        return user.getId();
    }

    /**
     * 用户登陆
     * @param userLoginReq
     * @return
     */
    @Override
    public LoginUserVO userLogin(UserLoginReq userLoginReq, HttpServletRequest request) {
        //1、校验
        if (StrUtil.hasBlank(userLoginReq.getUserAccount(), userLoginReq.getUserPassword())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userLoginReq.getUserAccount().length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号错误");
        }
        if (userLoginReq.getUserPassword().length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码错误");
        }
        //2、对用户传递的密码进行加密
        String userPassword = getEncryptPassword(userLoginReq.getUserPassword());
        //3、查询数据哭用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userLoginReq.getUserAccount());
        queryWrapper.eq("userPassword", userPassword);
        User user = this.baseMapper.selectOne(queryWrapper);

        //4、不存在，抛异常
        if (user == null){
            log.info("user login failed, userAccount cannot match userPassword!");
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在或者密码错误");
        }

        //5、保存用户登录状态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        return this.getLoginUserVO(user);
    }

    /**
     * 获取登录用户信息
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        //判断是否已经登陆
        Object userObject = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User cuurrentUser = (User) userObject;
        if (cuurrentUser == null || cuurrentUser.getId() == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"用户未登录");
        }
        //从数据库中查询用户信息
        Long userId = cuurrentUser.getId();
        cuurrentUser = this.getById(userId);
        if (cuurrentUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"用户未登录");
        }
        return cuurrentUser;
    }

    /**
     * 用户注销
     * @param request
     * @return
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }


    /**
     * 获取加密后的密码
     * @param userPassword
     * @return
     */
    @Override
    public String getEncryptPassword(String userPassword){
        //混淆密码，加盐
        final String SALT = "uisong";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    /**
     * 获取脱敏后的用户登录信息
     * @param user
     * @return
     */
    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null){
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtil.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    /**
     * 获取脱敏后的用户信息
     * @param user
     * @return
     */
    @Override
    public UserVO getUserVO(User user) {
        if (user == null){
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 获取脱敏后的用户信息列表
     * @param userList
     * @return
     */
    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)){
            return new ArrayList<>();
        }
        return userList.stream()
                .map(this::getUserVO)
                .collect(Collectors.toList());
    }

    /**
     * 获取查询条件
     * @param userQueryReq
     * @return
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryReq userQueryReq) {
        if (userQueryReq == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryReq.getId();
        String userAccount = userQueryReq.getUserAccount();
        String userName = userQueryReq.getUserName();
        String userProfile = userQueryReq.getUserProfile();
        String userRole = userQueryReq.getUserRole();
        String sortField = userQueryReq.getSortField();
        String sortOrder = userQueryReq.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

}




